package storage

import (
	"context"
	"fmt"
	"io"
	"net/http"
	"net/url"
	"time"

	"github.com/tencentyun/cos-go-sdk-v5"
)

type COS struct {
	client    *cos.Client
	secretID  string
	secretKey string
}

func NewCOS(bucketURL, secretID, secretKey string) COS {
	u, err := url.Parse(bucketURL)
	if err != nil {
		panic(err)
	}
	b := &cos.BaseURL{BucketURL: u}

	client := cos.NewClient(b, &http.Client{
		Transport: &cos.AuthorizationTransport{
			SecretID:  secretID,
			SecretKey: secretKey,
		},
	})

	return COS{
		client:    client,
		secretID:  secretID,
		secretKey: secretKey,
	}
}

func (c *COS) GetSignUrl(ctx context.Context, method string, filePath string, timeOut time.Duration) (signedURL string, err error) {
	presignedURL, err := c.client.Object.GetPresignedURL(ctx, method, filePath, c.secretID, c.secretKey, timeOut, nil)
	if err != nil {
		return "", err
	}
	return presignedURL.String(), nil
}

func (c *COS) Get(ctx context.Context, filePath string) (io.ReadCloser, error) {
	res, err := c.client.Object.Get(ctx, filePath, nil)

	var b io.ReadCloser
	if res != nil {
		b = res.Body
	}

	if err != nil {
		return b, err
	}

	if res.StatusCode >= 400 {
		return b, fmt.Errorf("got err response: %+v", res)
	}

	return b, nil
}
